import axios from "axios";
import store from "@/store";
import { logout } from "@/store/actions/user";
import history from "./history";
import { message } from "antd";

// 基础地址
export const baseURL = process.env.REACT_APP_URL
// 超时时间
const timeout = 5000
const request = axios.create({
    baseURL,
    timeout
})

// 请求拦截器
request.interceptors.request.use(config => {
    // 统一添加token在请求头
    const state = store.getState()
    if (state.user.token) {
      config.headers.Authorization = `Bearer ${state.user.token}`
    }
    return config
  }, e => Promise.reject(e))

// 响应拦截器
request.interceptors.response.use( res => {
    // 可选链操作符,取出需要的数据
    return res.data?.data || res
},e => {
  if (e.response.status === 401 && e.response.statusText === "Unauthorized") {
    // token失效
    message.error('登录失效')
    store.dispatch(logout())
    // 防止跳转login后才处理401
    if (history.location.pathname !== '/home') {
      history.push({
        pathname: '/login',
        state: { from: history.location.pathname }
      })
    }
  }
  return Promise.reject(e)
})

export default request